<template>
    <Form ref="formCom" class="xtx-form" :validation-schema="mySchema" v-slot="{errors}" autocomplete="off">
      <div class="user-info">
        <img :src="avatar" alt="" />
        <p>Hi，{{nickname}} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
      </div>
      <div class="xtx-form-item">
        <div class="field">
          <i class="icon iconfont icon-phone"></i>
          <Field :class="{err:errors.mobile}" v-model="form.mobile" name="mobile" class="input" type="text" placeholder="绑定的手机号" />
        </div>
        <div v-if="errors.mobile" class="error">{{ errors.mobile }}</div>
      </div>
      <div class="xtx-form-item">
        <div class="field">
          <i class="icon iconfont icon-code"></i>
          <Field :class="{err:errors.code}" v-model="form.code" class="input" name="code" type="text" placeholder="短信验证码" />
          <span class="code" @click="send()">发送验证码</span>
        </div>
        <div v-if="errors.code" class="error">{{ errors.code }}</div>
      </div>
      <a href="javascript:;" class="submit" @click="submit()">立即绑定</a>
    </Form>
  </template>
  
  <script>
  import {reactive, ref, onUnmounted} from 'vue'
  import schema from '@/utills/vee-validate-schema'
  import {Form, Field} from 'vee-validate'
  import {userQQBindCode, userQQBind} from '@/api/user'
  import { useIntervalFn } from '@vueuse/core'
  import Message from '@/components/library/xtx-message'
import store from '@/store'
  export default {
    name: 'CallbackBind',
    components: {Form, Field},
    props: {
      unionId: {
        type: String,
        default: ''
      }
    },
    setup (props) {
      //准备信息openId,qq头像、昵称
      //校验表单
      //发验证码，校验，定义api，调用，完成倒计时
      // 进行绑定，绑定成功就是登录成功
      const nickname = ref(null)
      const avatar = ref(null)
      
      // 表单数据对象
      const form = reactive({
        mobile: null,
        code: null
      })
      // 校验规则对象
      const mySchema = {
        mobile: schema.mobile,
        code: schema.code
      }

      //检查QQ是否登录
      if(QC.Login.check()) {
        // 获取QQ头像昵称
        QC.api('get_user_info').success(res => {
          avatar.value = res.data.figureurl_1
          nickname.value = res.data.nickname
        })
      }

      //有账号未登录 点击发送验证码
        //pause暂停, resume开始
        const formCom = ref(null)
        const time = ref(0)
        const {pause, resume} = useIntervalFn(() => {
            time.value--
            if(time.value = 0) {
              time.value = 0
                //暂停
                pause()
            }
        }, 1000, false)
        onUnmounted(() => {
            pause()
        })
        const send = async () => {
            //校验手机号
            const vaild = mySchema.mobile(form.mobile)
            //手机号校验成功，进入倒计时
            if(vaild === true) {
                if(time.value === 0) {
                    //获取短信登录验证码
                    await userQQBindCode(form.mobile)
                    Message({type: 'success', text: '发送成功'})
                    //开启倒计时
                    time.value = 60
                    resume()
                }
            } else {
                formCom.value.setFieldError('mobile', vaild)
            }
        }

        //立即绑定
        const submit = () => {
          //校验表单
          const vaild = formCom.value.validate()
          if(vaild) {

            // 校验成功，发请求
            userQQBind({unionId: props.unionId, ...form}).then(data => {

              //成功存储信息
              const { id, account, avatar, mobile, nickname, token } = data.result
              store.commit('user/setUser', { id, account, avatar, mobile, nickname, token })
              //合并购物车
              store.dispatch('cart/mergeCart').then(() => {
                  //跳转页面
                router.push(route.query.redirectUrl || '/')
                Message({type: 'success', text: '绑定成功'})
              })
              
            }).catch (e => {
              // 失败提示
                    Message({ type: 'error', text: e.response.data.message || '绑定失败' })
            }) 
          }
        }





      return {nickname, avatar, form, mySchema, time, send, formCom, submit}

    }
  }
  </script>
  
  <style scoped lang='less'>
  .user-info {
      width: 320px;
      height: 70px;
      margin: 0 auto;
      display: flex;
      background: #f2f2f2;
      align-items: center;
      padding: 0 10px;
      margin-bottom: 25px;
      img {
        background: #f2f2f2;
        width: 50px;
        height: 50px;
      }
      p {
        padding-left: 10px;
      }
    }
    .code {
      position: absolute;
      right: 0;
      top: 0;
      line-height: 50px;
      width: 80px;
      color: #999;
      &:hover {
        cursor: pointer;
      }
    }
  </style>